import React from 'react';

import {Pagination, Button, Table, Modal} from 'antd';
import Operation from './Operation';
import InputEx from './InputEx';
import SelectEx from './SelectEx';
import FileEx from './FileEx';
import CascaderEx from './CascaderEx';

import {emitter} from './myEmitter';

import styles from './index.less';

export default class ObjectList extends React.Component{
  state = {
    pagination:{},
    loading:true,
    rowdata:[],
    filters:null,
    sorter:null
  }

  async syncData(pagination, filters, sorter){
    var {current, pageSize} = pagination;
    current = current?current:1;
    pageSize = pageSize?pageSize:10;

    var ret = await this.props.fetchData(current, pageSize, filters, sorter);
    pagination.total = ret.data.count;

    this.setState({
      loading:false,
      rowdata:ret.data.content,
      pagination:pagination
    })
  }

  iemi = null;

  componentWillMount(){
    this.syncData(this.state.pagination);

    this.iemi = emitter.addListener('reload', ()=>{
      this.syncData(this.state.pagination);
    });
  }

  componentWillUnmount(){
    this.iemi.remove();
  }

  async tableOnChange(pagination, filters, sorter){
    var p = this.state.pagination;

    if (p.current != pagination.current || p.total !=  pagination.total || p.pageSize != pagination.pageSize || filters || sorter){
      this.setState({
        loading:true
      });

      await this.syncData(pagination, filters, sorter);
    }
  }



  render(){    
    return <Table
      columns = {this.props.columns}
      pagination = {this.state.pagination}
      dataSource = {this.state.rowdata}
      onChange = {(p,f,s)=>this.tableOnChange(p,f,s)}
    />
  }
}

ObjectList.Operation = Operation;
ObjectList.InputEx = InputEx;
ObjectList.SelectEx = SelectEx;
ObjectList.FileEx = FileEx;
ObjectList.Emitter = emitter;
